using admin.core.Entities;
using admin.core.Repositories;
using admin.infrastructure.Data;
using admin.core.Common;
using Microsoft.EntityFrameworkCore;

namespace admin.infrastructure.Repositories;
public class EfRepository<T> : IRepository<T> where T : EntityBase
{
    // 需要数据上下文
    private readonly DemoDbContext _db;
    private readonly DbSet<T> _tb;
    public EfRepository(DemoDbContext db)
    {
        _db = db;
        _tb = db.Set<T>();
    }

    // 查询所有
    public async Task<List<T>> GetAllAsync()
    {
        var list = await _tb.AsNoTracking().ToListAsync();
        return list;
    }

    // 查询一个
    public async Task<T>? GetByIdAsync(Guid id)
    {
        var obj = await _tb.FindAsync(id);

        return obj;
    }

    // 新增一个
    public async Task<T> AddAsync(T entity)
    {
        var obj = await _tb.AddAsync(entity);
        await _db.SaveChangesAsync();
        return obj.Entity;
    }

    // 修改一个
    public async Task UpdateAsync(T entity)
    {
        entity.UpdatedAt = DateTime.UtcNow;
        _tb.Update(entity);
        await _db.SaveChangesAsync();
    }

    // 删除一个
    public async Task DeleteAsync(T entity)
    {
        entity.IsDeleted = true;
        await UpdateAsync(entity);
    }

    // 根据ID删除一个
    public async Task<bool> DeleteAsync(Guid id)
    {
        try
        {
            var entity = await _tb.FindAsync(id);
            if (entity != null)
            {
                entity.IsDeleted = true;
                entity.UpdatedAt = DateTime.UtcNow;
                _tb.Update(entity);
                await _db.SaveChangesAsync();
                return true;
            }
            return false;
        }
        catch
        {
            return false;
        }
    }

    // 分页查询
    public async Task<PaginationResult<T>> GetPagedAsync(PaginationRequest request)
    {
        var query = _tb.AsNoTracking().Where(x => !x.IsDeleted);
        
        // 添加搜索条件
        if (!string.IsNullOrEmpty(request.SearchTerm))
        {
            query = query.Where(x => x.ToString().Contains(request.SearchTerm));
        }
        
        var totalCount = await query.CountAsync();
        var items = await query.Skip(request.Skip).Take(request.PageSize).ToListAsync();
        
        return new PaginationResult<T>(items, totalCount, request.PageNumber, request.PageSize);
    }
}